﻿import React, { useState, useRef, useEffect } from 'react';
import { Row, Col } from 'antd';
import { Image } from 'antd';
import ReactEcharts from 'echarts-for-react';
import { useLocation } from 'react-router-dom';

function StatsPage() {

  // 从路由中提取状态
  const location = useLocation();
  const state = location.state;

  // 调试，输出状态，包含数据
  console.log(state);

  // 组件状态管理
  const [ctime, setCtime] = useState(0);
  const [cidx, setCidx] = useState(0);

  // 视频引用
  const videoref = useRef(null);

  // 保存视频ID到本地存储
  localStorage.setItem('video_id', state.video_id);

  // 调试，输出数据
  console.log("1111111", state.data);

  // // 测试数据
  // const testData = {
  //   labels: ['人数', '车数'],
  //   barData: [120, 132, 101, 134, 90, 230, 210],
  //   lineData: [220, 182, 191, 234, 290, 330, 310],
  //   pieData: [
  //     {
  //       name: '总车数', value: state.data.filter((item) => item[4] && item[4] === 'car')
  //         .reduce((arr, item) => {
  //           if (!(item.id in arr)) {
  //             arr.push(item.id);
  //           }
  //           return arr;

  //         }, []).length
  //     },
  //     {
  //       name: '总人数', value: state.data.filter((item) => item[4] && item[4] === 'person')
  //         .reduce((arr, item) => {
  //           if (!(item.id in arr)) {
  //             arr.push(item.id);
  //           }
  //           return arr;
  //         }, []).length
  //     },
  //   ],
  // };

  // 获取真实数据
  const currentFrame = state.data[cidx].bboxes;
  const currentPersonCount = currentFrame.filter(item => item[4] === 'person').length;
  const currentCarCount = currentFrame.filter(item => item[4] === 'car').length;
  const correntTruckCount = currentFrame.filter(item => item[4] === 'truck').length;

  // 处理所有数据
  const allTimes = state.data.map(item => item.time);
  const allPersons = state.data.map(item => item.bboxes.filter(bbox => bbox[4] === 'person').length);
  const allCars = state.data.map(item => item.bboxes.filter(bbox => bbox[4] === 'car').length);
  const allTrucks = state.data.map(item => item.bboxes.filter(bbox => bbox[4] === 'truck').length);

  // 去重后的总数
  const uniquePersons = new Set(state.data.flatMap(item => item.bboxes.filter(bbox => bbox[4] === 'person').map(bbox => bbox[5]))).size;
  const uniqueCars = new Set(state.data.flatMap(item => item.bboxes.filter(bbox => bbox[4] === 'car').map(bbox => bbox[5]))).size;
  const uniqueTrucks = new Set(state.data.flatMap(item => item.bboxes.filter(bbox => bbox[4] === 'truck').map(bbox => bbox[5]))).size;

  // 处理柱状图数据
  const barOptions = {
    color: ['#5793f3'],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: ['人数', '车数', '卡车数'],
      axisTick: {
        alignWithLabel: true,
      },
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '数据统计',
        type: 'bar',
        barWidth: '60%',
        data: [currentPersonCount, currentCarCount, correntTruckCount],
      },
    ],
  };

  // 处理折线图数据
  const lineOptions = {
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: ['人数', '车数', '卡车数'],
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: allTimes,
    },
    yAxis: {
      type: 'value',
    },
    series: [
      {
        name: '人数',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series',
        },
        data: allPersons,
      },
      {
        name: '车数',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series',
        },
        data: allCars,
      },
      {
        name: '卡车数',
        type: 'line',
        stack: '总量',
        areaStyle: {},
        emphasis: {
          focus: 'series',
        },
        data: allTrucks,
      },
    ],
  };

  // 处理饼图数据
  const pieOptions = {
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'left',
    },
    series: [
      {
        name: '访问来源',
        type: 'pie',
        radius: '75%',
        center: ['50%', '60%'],
        data: [
          { value: uniquePersons, name: '总人数' },
          { value: uniqueCars, name: '总车数' },
          { value: uniqueTrucks, name: '总卡车数' },
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };

  // 根据当前时间更新当前索引
  useEffect(() => {
    for (let i = 0; i < state.data.length; i++) {
      if (ctime >= parseFloat(state.data[i].time)) {
        setCidx(i);
      }
    }
  }, [ctime]);

  // 处理视频的时间更新
  const handleTimeUpdate = (time) => {
    // console.log(time);
    console.log(videoref.current.currentTime);
    setCtime(videoref.current.currentTime);
  }

  return (
    <div>
      <Row gutter={[32, 32]} >
        <Col span={6}>
        <h3>当前人脸</h3>
        </Col>
        <Col span={12}>
        <h3>检测结果</h3>
        </Col>
        <Col span={6}>
        <h3>当前车牌</h3>
        </Col>

        <Col span={6} >
          <Image width="100%" height={266} src={state.data[cidx].type === 'face' ? state.data[cidx].image_url : ''}
            fallback=""
            style={{
              objectFit: 'contain'
            }}
          />
        </Col>
        <Col span={12} >
          <video width="100%" height={'265px'} controls ref={videoref} onTimeUpdate={handleTimeUpdate}>
            <source src={state.url} type="video/mp4" />
          </video>
        </Col>
        <Col span={6}>
          <Image width="100%" height={266} src={state.data[cidx].type === 'car' ? state.data[cidx].image_url : ''}
            fallback=""
            style={{
              objectFit: 'contain'
            }}
          />
        </Col>
        <Col span={8}>
          <ReactEcharts option={barOptions} style={{ height: '400px' }} />
        </Col>
        <Col span={8}>
          <ReactEcharts option={lineOptions} style={{ height: '400px' }} />
        </Col>
        <Col span={8}>
          <ReactEcharts option={pieOptions} style={{ height: '400px' }} />
        </Col>
      </Row>

    </div>
  );
}

export default StatsPage;